package com.cskaoyan.app.advice;

import com.cskaoyan.app.bean.common.BaseRespVo;
import com.cskaoyan.app.bean.po.*;
import com.cskaoyan.app.mapper.*;
import org.aopalliance.intercept.Joinpoint;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author kiggy
 * @since 2022/12/31 15:42
 */
@Component
@Aspect
public class LogAspectJAdvice {

    @Autowired
    MarketLogMapper logMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    MarketAdminMapper adminMapper;

    @Autowired
    MarketRoleApiMapper apiMapper;

    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketOrderMapper orderMapper;

    @Autowired
    MarketAPIMapper rbacMapper;

    /**
     * 将当前商品写入到footprint数据库中
     * 内容包括：userid,goodsid,addtime,updatetime,deleted
     * 需要将所浏览的商品的updatetime更新
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("cutWxGoods()")
    public Object wxGoodsAop(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();
        if (!(result instanceof BaseRespVo)) {
            return result;
        }
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null) {
            return result;
        }
        // 先进行判断当前商品是否已浏览过，是的话，直接更新字段：updateTime
        String goodsId = request.getParameter("id");
        MarketFootprintExample footprintExample = new MarketFootprintExample();
        MarketFootprintExample.Criteria criteria = footprintExample.createCriteria();
        criteria.andGoodsIdEqualTo(Integer.valueOf(goodsId));
        List<MarketFootprint> footprints = footprintMapper.selectByExample(footprintExample);
        if (footprints.size()!=0) {
            if (footprints.get(0) != null) {
                MarketFootprint footprint = new MarketFootprint();
                footprint.setUpdateTime(new Date());
                footprint.setId(footprints.get(0).getId());
                footprint.setDeleted(false);
                footprintMapper.updateByPrimaryKeySelective(footprint);
                return result;
            }
        }

        // 获得参数：userid,goodsid,addtime,updatetime,deleted
        Integer userid = (Integer) subject.getSession().getAttribute("userid");

        // 为list赋值
        MarketFootprint marketFootprint = new MarketFootprint();
        marketFootprint.setUserId(userid);
        marketFootprint.setGoodsId(Integer.parseInt(goodsId));
        marketFootprint.setAddTime(new Date());
        marketFootprint.setUpdateTime(new Date());
        marketFootprint.setDeleted(false);
        footprintMapper.insertSelective(marketFootprint);

        return result;
    }


    @Around("cutAdminLogin()")
    public Object adminAop(ProceedingJoinPoint joinPoint) throws Throwable {
        String uri = request.getRequestURI();
        Object result = joinPoint.proceed();
        if (!uri.startsWith("/admin")){
            return result;
        }
        if (!(result instanceof BaseRespVo)) {
            return result;
        }
        BaseRespVo respVo = (BaseRespVo) result;
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null) {
            return result;
        }
        // 获得所以参数
        String admin = (String) principals.getPrimaryPrincipal();
        int errno = respVo.getErrno();
        String ip = request.getRemoteAddr();
        String resultStr;
        String uriFormat = uri.replace("/", ":");
        String substring = uriFormat.substring(1);
        String action = rbacMapper.getLabelById(substring);
        if (uriFormat.endsWith("login")){
            action = "登录";
        }
        if (action==null){
            return result;
        }
        boolean status = true;
        Date date = new Date();

        // 内容包括：id,admin,ip,type,action,status,result,comment,addTime,updateTime,deleted
        MarketLog marketLog = new MarketLog();
        // marketLog.setId(id);
        // marketLog.setAdmin(admin);
        // 如果errno是0，说明登录状态是成功——>true

        if (errno == 0){
            marketLog.setStatus(true);
        }else {
            marketLog.setStatus(false);
            resultStr = respVo.getErrmsg();
            marketLog.setResult(resultStr);
        }
        marketLog.setIp(ip);
        marketLog.setType(1);
        marketLog.setAction(action);
        marketLog.setStatus(status);
        marketLog.setUpdateTime(date);
        marketLog.setAddTime(date);
        marketLog.setAdmin(admin);
        // 向数据库添加数据
        logMapper.insertSelective(marketLog);
        return result;
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void cutAdminLogin() {
    }

    @Pointcut("execution(* com.cskaoyan.app.wxcontroller.WxGoodsController.detail(..))")
    public void cutWxGoods() {
    }


}
